<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Model extends CI_Model {

	protected $_table_name = '';

	public function __construct() {
		parent::__construct();
	}

	public function get($id='', $prefix='') {
		$this->__check_table_name();
		if (empty($id)) {
			$fields = $this->db->list_fields($this->_table_name);
			$retval = array();
			foreach ($fields as $field) {
				$retval[$field] = '';
			}
			return $retval;
		}
		$this->db->where($prefix.'id', $id);
		$rs = $this->db->get($this->_table_name);
		return $rs->row_array();
	}

	public function lists($conditions='', $order_by='', $limit='', $offset='', $school_year_id = '', $select_field='*', $join_table='') {
		$this->__check_table_name();
		if (!empty($conditions)) {
			$this->db->where($conditions);
		}
		if (!empty($school_year_id)) {
			$this->db->where('school_year_id',$school_year_id);
		}
		if (!empty($order_by)) {
			$this->db->order_by($order_by);
		}
		$this->db->select($select_field);
		$rs = $this->db->from($this->_table_name . $join_table);
		if (!empty($limit)) {
			$this->db->limit($limit,$offset);
		}
		$rs = $this->db->get();
		return $rs->result_array();
	}

	public function is_unique_value_on_field($field, $value, $id='') {
		$this->__check_table_name();
		if (!empty($id)) {
			$this->db->where('id !=', $id);
		}
		$this->db->where($field, $value);
		return $this->db->count_all_results($this->_table_name) > 0;
	}

	public function insert(&$input, $overwrites=array(), $prefix='') {
		$fields = $this->db->list_fields($this->_table_name);
		foreach ($fields as $field) {
			$data[$field] = $input->post("{$prefix}{$field}");
		}
		$data = array_merge($data, $overwrites);
		$this->db->insert($this->_table_name, $data);
	}

	public function update(&$input, $update_id, $overwrites=array(), $prefix='') {
		$fields = $this->db->list_fields($this->_table_name);
		foreach ($fields as $field) {
			$data[$field] = $input->post("{$prefix}{$field}");
		}
		$data = array_merge($data, $overwrites);
		$this->db->update($this->_table_name, $data, array('id'=>$update_id));
	}

	public function delete($id) {
		$this->db->delete($this->_table_name, array('id'=>$id));
	}

	public function last_inserted_id() {
		$this->db->select_max('id');
		$rs  = $this->db->get($this->_table_name);
		$row = $rs->row_array();
		return $row['id'];
	}

	private function __check_table_name() {
		if (empty($this->_table_name)) {
			die('[ERROR:core/MY_Model.php] You must set table name for ' . get_class($this));
		}
	}

	protected function _encrypt($password) {
		return md5($password);
	}

	public function _count($conditions=''){
		$this->__check_table_name();
		if (!empty($conditions)) {
			$this->db->where($conditions);
		}
		return $this->db->count_all_results($this->_table_name);
	}
}
